package com.cyl.manager.pms.service;

import java.util.*;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import io.swagger.annotations.ApiModelProperty;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.cyl.h5.domain.vo.ProductDetailVO;
import com.cyl.manager.act.domain.entity.CouponCategory;
import com.cyl.manager.act.mapper.CouponCategoryMapper;
import com.cyl.manager.act.service.CouponCategoryService;
import com.cyl.manager.oms.domain.entity.Order;
import com.cyl.manager.oms.domain.entity.OrderItem;
import com.cyl.manager.oms.mapper.OrderItemMapper;
import com.cyl.manager.oms.mapper.OrderMapper;
import com.cyl.manager.pms.convert.ProductConvert;
import com.cyl.manager.pms.domain.entity.Sku;
import com.cyl.manager.pms.mapper.BrandMapper;
import com.cyl.manager.pms.mapper.SkuMapper;
import com.cyl.manager.pms.domain.vo.ProductVO;
import com.github.pagehelper.PageHelper;
import com.ruoyi.common.annotation.Excel;
import com.ruoyi.common.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import com.cyl.manager.pms.mapper.ProductMapper;
import com.cyl.manager.pms.domain.entity.Product;
import com.cyl.manager.pms.domain.query.ProductQuery;
import org.springframework.transaction.annotation.Transactional;

/**
 * 商品信息Service业务层处理
 *
 *
 * @author zcc
 */
@Service
@Slf4j
public class ProductService {
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private OrderItemMapper orderItemMapper;
    @Autowired
    private SkuMapper skuMapper;
    @Autowired
    private BrandMapper brandMapper;
    @Autowired
    private ProductConvert convert;

    @Autowired
    private CouponCategoryService couponCategoryService;
    /**
     * 查询商品信息
     *
     * @param id 商品信息主键
     * @return 商品信息
     */
    public Product getById(Long id) {
        Product product = productMapper.selectById(id);
        return product;
    }
    
    
    /**
     * 查询商品信息
     *
     * @param id 商品信息主键
     * @return 商品信息
     */
    public ProductVO selectById(Long id) {
        Product product = productMapper.selectById(id);
        ProductVO productVO = convert.do2vo(product);
		 if(productVO.getCplx()!=null && productVO.getDhCouponCategoryId()!=null) {
         	CouponCategory couponCategory = couponCategoryService.selectCheckById(productVO.getDhCouponCategoryId());
         	if(couponCategory!=null) {
         		productVO.setFlqmc(couponCategory.getTitle());
         	}
         }
        QueryWrapper<Sku> qw = new QueryWrapper<>();
        qw.eq("product_id", product.getId());
        List<Sku> skus = skuMapper.selectList(qw);
        productVO.setSkuList(skus);
        return productVO;
    }

    /**
     * 查询商品信息列表
     *
     * @param query 查询条件
     * @param page 分页条件
     * @return 商品信息
     */
    public List<Product> selectList(ProductQuery query, Pageable page) {
        if (page != null) {
            PageHelper.startPage(page.getPageNumber() + 1, page.getPageSize());
        }
        QueryWrapper<Product> qw = new QueryWrapper<>();
        if(query.getCxhszsp()!=null && query.getCxhszsp()==1) {
        	  qw.eq("del_flag", 2);//查询回收站商品
        }else {
        	  qw.eq("del_flag", 0);
        }
        if (StringUtils.isNoneEmpty(query.getOrderField())){
            if (StringUtils.isNotEmpty(query.getOrderSort()) && "desc".equalsIgnoreCase(query.getOrderSort())) {
                qw.orderByDesc(query.getOrderField());
            } else {
                qw.orderByAsc(query.getOrderField());
            }
        }else {
            qw.orderByDesc("publish_status");
            qw.orderByAsc("sort");
        }
        Long deptDpId = query.getDeptDpId();
        if(deptDpId!=null) {
        	 qw.and(wrapper->
        	 		wrapper.isNull("kjdpids")
  		           .or().eq("kjdpids", "").or() 
  		           .like("kjdpids", ","+deptDpId+","));
        }
       
    	
        
        
        Long id = query.getId();
        if (id != null) {
            qw.eq("id", id);
        }
        

        Long createBy = query.getCreateBy();
          if (createBy != null) {
              qw.eq("create_by", createBy);
          }
          
        Long brandId = query.getBrandId();
        if (brandId != null) {
            qw.eq("brand_id", brandId);
        }
        
        String outProductId = query.getOutProductId();
        if (StringUtils.isNoneEmpty(outProductId)){
            qw.eq("out_product_id", outProductId);
        }
        
        
        Long dhCouponCategoryId = query.getDhCouponCategoryId();
        if (dhCouponCategoryId != null) {
            qw.eq("dh_coupon_category_id", dhCouponCategoryId);
        }
        
        String cplx = query.getCplx();
        if (StringUtils.isNoneEmpty(cplx)){
            qw.eq("cplx", cplx);
        }
        
        
        
        Long categoryId = query.getCategoryId();
        if (categoryId != null) {
            qw.eq("category_id", categoryId);
        }
        
        Long qrDeptZbjId = query.getDeptZbjId();
        if(qrDeptZbjId!=null) {
            qw.eq("dept_zbj_id", qrDeptZbjId);
        }
        Integer publishStatus = query.getPublishStatus();
        if (publishStatus != null) {
            qw.eq("publish_status", publishStatus);
        }
        Integer memberPublishStatus = query.getMemberPublishStatus();
        if (memberPublishStatus != null) {
            qw.eq("member_publish_status", memberPublishStatus);
        }
        Integer shopPublishStatus = query.getShopPublishStatus();
        if (shopPublishStatus != null) {
            qw.eq("shop_publish_status", shopPublishStatus);
        }
        Integer hxyPublishStatus = query.getHxyPublishStatus();
        if (hxyPublishStatus != null) {
            qw.eq("hxy_publish_status", hxyPublishStatus);
        }
         
        String search = query.getSearch();
        if (StringUtils.isNoneEmpty(search)){
            qw.like("name", "%".concat(query.getSearch().trim()).concat("%"));
        }
        if (CollectionUtil.isNotEmpty(query.getExcludeProductIds())) {
            qw.notIn("id",query.getExcludeProductIds());
        }
        if (CollectionUtil.isNotEmpty(query.getIds())) {
            qw.in("id",query.getIds());
        }
        return productMapper.selectList(qw);
    }

    /**
     * 新增商品信息
     *
     * @param productVO 商品信息
     * @return 结果
     */
    @Transactional
    public int insert(ProductVO productVO) {

        Product product = convert.vo2do(productVO);
        product.setCreateTime(LocalDateTime.now());
        List<Sku> skuList = productVO.getSkuList();
        Long deptZbjId = SecurityUtils.getDeptZbjId();
        product.setDeptZbjId(deptZbjId);
        product.setDelFlag(0);
        productMapper.insert(product);
        if(skuList!=null){
            skuList.forEach(sku -> {
                sku.setProductId(product.getId());
                sku.setDeptZbjId(deptZbjId);
                sku.setCreateTime(LocalDateTime.now());
                skuMapper.insert(sku);
            });
        }
        return 1;
    }

    /**
     * 修改商品信息
     *
     * @param productVO 商品信息
     * @return 结果
     */
    @Transactional
    public int spsxj(ProductVO productVO) {
        Long userId = SecurityUtils.getUserId();
        UpdateWrapper<Product> updateWrapper = new UpdateWrapper<Product>();
        updateWrapper.set("update_by", userId);
        updateWrapper.set("update_time", LocalDateTime.now());
        updateWrapper.set("publish_status", productVO.getPublishStatus());
        updateWrapper.eq("id", productVO.getId());
        return productMapper.update(null, updateWrapper);
       
    }

   
    
    /**
     * 修改商品信息
     *
     * @param productVO 商品信息
     * @return 结果
     */
    @Transactional
    public int update(ProductVO productVO) {
        Product dbProduct = productMapper.selectById(productVO.getId());
        List<Long> idList = productVO.getSkuList().stream().filter(it -> it.getId() != null).map(it -> it.getId()).collect(Collectors.toList());
        if (dbProduct == null) {
            return 0;
        }
        Long userId = SecurityUtils.getUserId();
        Product product = convert.vo2do(productVO);
        List<Sku> skuList = productVO.getSkuList();
        product.setUpdateBy(userId);
        product.setUpdateTime(LocalDateTime.now());
        productMapper.updateById(product);
        //查找库中所有的sku
        Map<String,Object> map = new HashMap<>();
        map.put("product_id", product.getId());
        Map<Long, Sku> skuMap = skuMapper.selectByMap(map).stream().collect(Collectors.toMap(it -> it.getId(), it -> it));
        //针对已有的进行编辑
        List<Sku> updateList = productVO.getSkuList().stream().filter(it -> it.getId() != null).collect(Collectors.toList());
        if (!CollectionUtil.isEmpty(updateList)) {
            log.info("共有{}个sku需要修改，{}，productId：{}",updateList.size(), JSONUtil.toJsonStr(updateList),productVO.getId());
            updateList.forEach(it->{
                Sku sku = skuMap.get(it.getId());
                sku.setUpdateBy(SecurityUtils.getUserId());
                sku.setUpdateTime(LocalDateTime.now());
                sku.setPrice(it.getPrice());
                sku.setSpData(it.getSpData());
                sku.setPic(it.getPic());
                sku.setOutSkuId(it.getOutSkuId());
                sku.setStock(it.getStock());
                sku.setOriginalprice(it.getOriginalprice());
                sku.setCgprice(it.getCgprice());
                sku.setDhCouponCategoryNum(it.getDhCouponCategoryNum());
                sku.setDhJssl(it.getDhJssl());
                sku.setDpjsprice(it.getDpjsprice());
                skuMapper.updateById(sku);
            });
        }
        //针对没有的进行新增
        List<Sku> addList = productVO.getSkuList().stream().filter(it -> it.getId() == null).collect(Collectors.toList());
        if (!CollectionUtil.isEmpty(addList)) {
            log.info("共有{}个sku需要新增，{}，productId：{}",addList.size(), JSONUtil.toJsonStr(addList),productVO.getId());
            addList.forEach(sku -> {
                sku.setDeptZbjId(dbProduct.getDeptZbjId());
                sku.setProductId(product.getId());
                sku.setCreateTime(LocalDateTime.now());
                skuMapper.insert(sku);
            });
        }
        //删除
        List<Long> deleteIds = skuMap.keySet().stream().filter(it -> !idList.contains(it)).collect(Collectors.toList());
        if (!CollectionUtil.isEmpty(deleteIds)) {
            log.info("共有{}个sku需要删除，{}，productId：{}",deleteIds.size(), JSONUtil.toJsonStr(deleteIds),productVO.getId());
            skuMapper.deleteBatchIds(deleteIds);
        }
        return 1;
    }

    /**
     * 删除商品信息信息
     *
     * @param id 商品信息主键
     * @return 结果
     */
    public int deleteById(Long id) {
    	
    	QueryWrapper<OrderItem> queryWrapper = new QueryWrapper<OrderItem>();
    	queryWrapper.eq("product_id", id);
    	if(orderItemMapper.selectCount(queryWrapper)>0) {
            throw new RuntimeException("有订单关联不能删除");
    	}
    	
    	UpdateWrapper<Product> updateWrapper = new UpdateWrapper<Product>();
    	updateWrapper.eq("id", id);
    	updateWrapper.set("del_flag", 2);
    	
    	return productMapper.update(null, updateWrapper);
        // return productMapper.deleteById(id);
    }
    
    /**
     * 删除回收站商品信息信息
     *
     * @param id 商品信息主键
     * @return 结果
     */
    public int deleteHszById(Long id) {
    	
    	QueryWrapper<OrderItem> queryWrapper = new QueryWrapper<OrderItem>();
    	queryWrapper.eq("product_id", id);
    	if(orderItemMapper.selectCount(queryWrapper)>0) {
            throw new RuntimeException("有订单关联不能删除");
    	} 
    	
        return productMapper.deleteById(id);
    }
    

    public ProductDetailVO queryDetail(Long id) {
        ProductDetailVO res = new ProductDetailVO();
        Product d = productMapper.selectById(id);
        res.setProduct(d);
        LambdaQueryWrapper<Sku> qw = new LambdaQueryWrapper<>();
        qw.eq(Sku::getProductId, id);
        res.setSkus(skuMapper.selectList(qw));
        if (d.getBrandId() != null) {
            res.setBrand(brandMapper.selectById(d.getBrandId()));
        }
        if(d.getCplx()!=null && d.getDhCouponCategoryId()!=null) {
        	CouponCategory couponCategory = couponCategoryService.selectCheckById(d.getDhCouponCategoryId());
        	if(couponCategory!=null) {
        		res.setFlqmc(couponCategory.getTitle());
        	}
        }
        return res;
    }
}
